package com.talkyun.openx.server.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class SessionManager {
    private static final Logger logger = LoggerFactory.getLogger(SessionManager.class);
    private static final Map<String, Session> ID2SESSION = new ConcurrentHashMap<String, Session>();
    private static final SessionManager instance = new SessionManager();

    private SessionManager() {
    }

    public static SessionManager get() {
        return instance;
    }

    public Session getSession(String sessionId) {
        Session session = ID2SESSION.get(sessionId);
        if (session == null) {
            // lazy generate
            logger.info("=> Create session {} .", sessionId);
            session = new Session(sessionId);
            ID2SESSION.put(sessionId, session);
        }
        return session;
    }

    public void clean(String sessionId) {
        ID2SESSION.remove(sessionId);
        logger.info("=> Clean session {} !", sessionId);
    }

    public void updateActiveTime(String sessionId) {
        Session session = ID2SESSION.get(sessionId);
        if (session != null) {
            session.setLastActiveTime(System.currentTimeMillis());
        }
    }

    Set<Map.Entry<String, Session>> getAllSession() {
        return ID2SESSION.entrySet();
    }
}